package fr.ssd.sdl.store.file;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

import fr.ssd.sdl.store.Store;
import fr.ssd.sdl.store.StoreException;

public class FileBackend implements Store {

	protected static final String storeFileName = "storeFileName";

	BufferedWriter w;

	@Override
	public void store(String sqlStatement) throws StoreException {
		try {
			w.write(sqlStatement);
			w.newLine();
		} catch (IOException e) {
			throw new StoreException(e);
		}
	}

	/**
	 * @param hints
	 *            the initialization context. This implementation require the
	 *            context to contain an entry with the key "storeFileName" and a
	 *            value containing the local uri where the store file will be
	 *            created. Key and value must be {@code java.lang.String}
	 *            objects {@code <"storeFileName","path/to/store.sql">}
	 */
	@Override
	public void init(Map<String, ?> hints) throws StoreException {
		String fileName = (String) hints.get(storeFileName);
		try {
			this.w = new BufferedWriter(new FileWriter(fileName));
		} catch (IOException e) {
			throw new StoreException(e);
		}
	}

	@Override
	public void terminate() throws StoreException {
		try {
			w.close();
		} catch (IOException e) {
			throw new StoreException(e);
		}
	}

}
